<?php
namespace app\api\controller\orderdelivery;
use think\File;
use think\facade\Env;
use app\common\model\user\User as UserModel;
use app\common\model\company\Company;
use app\common\model\orderdata\Goods;
use app\common\model\quotation\QuotationList;
use app\api\controller\Base;
use app\common\model\orderdelivery\Disposalsite;
use app\common\model\orderdelivery\DeliveryList;
use app\common\model\orderdelivery\Delivery;
use app\common\model\cost\Costtype;
use app\common\model\cost\Pay;
use app\common\model\cost\Revenue;
use app\common\model\power\Rolepower;
use app\api\controller\mytool\Sendmessage;
use app\common\model\orderdata\StorageAreaGoods;

class Orderdeliveryacco extends Base
{
	/**
	 * 初始化
	 */
    public function initialize(){
		parent::initialize();
		self::is_login();
		Rolepower::powerguard(203005);
	}
	/**
	 * 获取订单列表
	 * @return [type] [description]
	 */
	public function list(){
		$data = input('get.');
		$data = init_where($data);
		$list = DeliveryList::usergetlist($data,'acco');
		foreach ($list['list'] as $key => $value) {
			if(empty($value['dispinfo']['DisposalSiteName'])){
				$list['list'][$key]['Name'] = '暂无';
			}else{
				$list['list'][$key]['Name'] = $value['dispinfo']['DisposalSiteName'];
			}
		}
		$list['tr']['title']  = ['产废单位','提单时间','订单状态','查看','出库时间','结算时间','合计费用'];
		$list['tr']['key'] = ['Name','UpTime','State','DeliveryListId','WarehouseTime','SettlementTime','TotalCost'];
		$list['tr']['show']=[true,true,true,true,false,false,false,false];
		return myok($list);
	}

	/**
	 * 补录回执
	 * @return [type] [description]
	 */
	public function revenue(){
		$idata = input('post.');
		$id = input('id');
		if(empty($id)){
			return myerr('缺少重要参数，请重新尝试');
		}
		$data = DeliveryList::getinfo($id,'acco');
		if(!$data['code']){
			return myerr($data['msg']);
		}
		$data = $data['msg'];
		// if($data['State']==DeliveryList::STATEOK){
		// 	return myerr('订单已完成无法修改');
		// }
		//修改子订单信息
		$QuotationCost = 0;
		$delivery = explode(',',$idata['DeliveryId']);
		$ReceiptWeight = explode(',',$idata['ReceiptWeight']);
		$ReceiptCost = explode(',',$idata['ReceiptCost']);
		$nddata = [];
		foreach ($delivery as $key => $value) {
			$nddata[$value]['weight'] = $ReceiptWeight[$key];
			$nddata[$value]['cost'] = $ReceiptCost[$key];
		}
		$ddata = Delivery::where('DeliveryListId',$id)->select();
		foreach ($ddata as $key => $value) {
			$value->ReceiptCost = $nddata[$value->DeliveryId]['cost'];
			$value->ReceiptWeight = $nddata[$value->DeliveryId]['weight'];
			$QuotationCost  = $QuotationCost + ($value->ReceiptCost *$value->ReceiptWeight);
			$value->save();
		}
		//修改主订单信息
		$rdata = [];
		$FloatingCost = input('FloatingCost');
		//检查订单总费用是否已经定义
		if(empty($data['TotalCost'])){
			$data['TotalCost'] = 0;
			$rdata['TotalCost'] = 0;
		}else{
			$rdata['TotalCost'] = $data['TotalCost'];
		}

		//浮差费用
		if(!empty($FloatingCost)&&$FloatingCost!==$data['FloatingCost']){
			$rdata['TotalCost'] = $rdata['TotalCost'] - $data['FloatingCost'] + $FloatingCost;
			$rdata['FloatingCost']  = $FloatingCost;
		}

		//货物总费用
		if($QuotationCost!==$data['QuotationCost']){
			$rdata['TotalCost'] = $rdata['TotalCost'] - $data['QuotationCost'] + $QuotationCost;
			$rdata['QuotationCost']  = $QuotationCost;
		}

		if(!empty(input('ReceiptImg'))&&input('ReceiptImg')!==$data['ReceiptImg']){
			$rdata['ReceiptImg']  = input('ReceiptImg');
		}

		if(!empty(input('ReceiptNote'))&&input('ReceiptNote')!==$data['ReceiptNote']){
			$rdata['ReceiptNote']  = input('ReceiptNote');
		}
		if(!empty($rdata)){
			$rdata['id'] = $id;
			$rdata['State']  = DeliveryList::STATEOK;
			DeliveryList::user_reinfo($rdata);
		}else{
			return myerr('没有需要修改的信息');
		}
		return myok('回执登记完成');
	}
	/**
	 * 获取创建的信息
	 * @return [type] [description]
	 */
	public function getcreateinfo(){
		$id = input('id');
		if(!empty($id)){
			$data = DeliveryList::getinfo($id,'acco');
			if(!$data['code']){
				return myerr($data['msg']);
			}else{
				$data = $data['msg'];
			}
		}

		$ndata['Type'] = 'disposalsite';
		$data['DisposalsiteList'] = Disposalsite::usergetlist($ndata,1,false);
		$data['StateList'] = DeliveryList::STATEARRAY;
		if(empty($data['State'])){
			$data['State'] = 0;
		}
		return myok($data);
	}
	/**
	 * 获取订单信息
	 * @return [type] [description]
	 */
	public function getinfo(){
		$id = input('id');
		if(empty($id)){
			return myerr('缺少参数，请重新尝试');
		}
		$data = DeliveryList::getinfo($id,'acco');
		if(!$data['code']){
			return myerr($data['msg']);
		}
		$data = $data['msg'];
		$data['CELLPHONE'] = CELLPHONE;
		return myok($data);
	}
	/**
	 * 创建出库提单
	 * @return [type] [description]
	 */
	public function createorder(){
		$idata = input('post.');
		$id = input('id');
		if(!empty($id)){
			//修改订单
			$data = DeliveryList::getinfo($id,'acco');
			if(!$data['code']){
				return myerr($data['msg']);
			}
			$data = $data['msg'];
			if($data['State']==DeliveryList::STATEOK){
				return myerr('订单已完成无法修改');
			}
			//修改主订单信息
			$rdata = [];
			$DisposalSiteId = input('DisposalSiteId');
			if(!empty($DisposalSiteId)&&(int)$DisposalSiteId!==$data['DisposalSiteId']){
				$rdata['DisposalSiteId']  = input('DisposalSiteId');
			}
			if(!empty(input('UpNote'))&&input('UpNote')!==$data['UpNote']){
				$rdata['UpNote']  = input('UpNote');
			}
			if(!empty($rdata)){
				$rdata['id'] = $id;
				DeliveryList::user_reinfo($rdata);
			}else{
				return myerr('没有需要修改的信息');
			}

			return myok('修改成功');
		}else{
			//新建出库提单
			$hawa = DeliveryList::screate($idata);
			if(!$hawa['code']){
				return myerr($hawa['msg']);
			}
			Sendmessage::Orderdelivery(1,$hawa['msg']['DeliveryListId'],$hawa['msg']);
			return myok('出库订单创建成功');
		}
	}

	/**
	 * 将订单状态从待回执中退回到待出库
	 * @return [type] [description]
	 */
	public function repulse(){
		$id = input('id');
		if(empty($id)){
			return myerr('缺少重要参数');
		}
		$data = DeliveryList::liststate($id);
		if(!$data['code']){
			return myerr($data['msg']);
		}
		$data = $data['msg'];
        if($data['State']!==DeliveryList::STATETRANSPORT){
        	return myerr('订单状态错误，无法退回至待出库');
        }
        //修改库存
        $list = Delivery::where('DeliveryListId',$id)->select();
        $goodlist =[];
        $valuelist = [];
        foreach ($list as $key => $value) {
        	$goodlist[] = $value['GoodId'];
        	$valuelist[] = $value['Weight'];
        	//修改库存区域表
        	$sag = StorageAreaGoods::get($value['StorageAreaGoodsId']);
        	$sag->Weight = ['inc', $value['Weight']];
        	$sag->save();
        }
        //修改货物表
        Goods::weight_change($goodlist,$valuelist);
        //修改主订单信息
		$rdata = [];
		$rdata['id'] = $id;
		$rdata['State'] = DeliveryList::STATEWAITOK;
		DeliveryList::user_reinfo($rdata);
		return myok('订单已修改为待出库');
	}
	/**
	 * 结算订单
	 * @return [type] [description]
	 */
	public function settlement(){
		$id = input('id');
		$data = DeliveryList::liststate($id);
		if(empty($data)){
			return myerr('没有找到需要的订单');
		}
		$data = $data['msg'];
		$rdata = [];
		$rdata['id'] = $id;
		if(!empty(input('SettlementImg'))){
			$rdata['SettlementImg']  = input('SettlementImg');
		}
		if(!empty(input('SettlementNote'))){
			$rdata['SettlementNote']  = input('SettlementNote');
		}
		if(!empty(input('autocost'))&&input('autocost')!=='false'&&empty($data['SettlementTime'])){
			$cost = $data['QuotationCost']+$data['FloatingCost'];
			if(empty($cost)){
		        return myerr('费用为空无需记录');
			}
			$sdata['TypeId'] = Costtype::getid('orderdelivery');
		    $sdata['PayTime'] = date("Y-m-d H:i",time());
		    $sdata['RelationUserId'] = '';
		    $sdata['RelationListId'] = $id;
		    if(!empty(input('SettlementImg'))){
				$sdata['UpImg'] = input('SettlementImg');
			}
			if(!empty(input('SettlementNote'))){
				$sdata['UpNote']   = input('SettlementNote');
			}
			if($cost>0){
		        $sdata['PayCost'] = $cost;
				Revenue::screate($sdata);
			}else{
				$sdata['PayCost'] = 0 - $cost;
				Pay::screate($sdata);
			}
		}
		$rdata['SettlementTime'] = date('Y-m-d H:i',time());
		DeliveryList::user_reinfo($rdata);
		//检查结算账单是否一致
		if(!empty($data['SettlementTime'])){
			return myok('已修改结算备注');
		}else{
			return myok('已结算');
		}
	}

	/**
	 * 图片上传
	 * @return [type] [description]
	 */
	public function upimg(){
		$type = empty(input('type'))?'other':input('type');
		if(!$type=='hawa'||!$type=='buss'||!$type=='acco'){
			$type = 'other';
		}
		try {
			$file = request()->file('img');
		} catch (\Exception $e) {
			return json_encode(['status'=>'error','data'=>$e->getMessage()]);
		}
        // 移动到框架应用根目录/public/uploads/ 目录下
        if(!is_null($file)){
           	try{
           		$save_path = Env::get('root_path').'public\\static' .'\\upimg\\hawa\\'.$type.'\\';
	            $info = $file->validate(["size"=>50000000,'ext'=>'jpg,png,gif'])->rule("date")->move($save_path);
	            //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
	            $image = \think\Image::open($save_path . '\\' . $info->getSaveName());  
	            $image->thumb(2000, 2000)->save($save_path .  '\\' . $info->getSaveName());  
	            if($info){//getSaveName();
	                $p=$info->getFilename();
	                return json_encode(['status'=>'ok','data'=>SERVERURL.'static/upimg/hawa/'.$type.'/'.date('Ymd',time()).'/'.$p]);
	            }else{
	              return json_encode(['status'=>'error','data'=>$info->getError()]);
	            }
           	} catch (\Exception $e) {
				return json_encode(['status'=>'error','data'=>$e->getMessage()]);
			}	
            
         }else{
              return json_encode(['status'=>'error','data'=>'没有找到需要上传的图片']);
         }
	}


	/**
	 * 判断账号是否登录
	 * @return boolean [description]
	 */
	private function is_login(){
		$data = UserModel::is_sessionlogin();
		if (!$data['code']) {
			$data['options'] = 'relogin';
			json($data)->send();
			exit;
		}
	}
}
